/**
 * 得到指定数组的分页信息对象
 * @param {*} arr 
 * @param {*} pageNum 
 * @param {*} pageSize 
 */
function pageFilter(arr, pageNum, pageSize) {
	pageNum = pageNum * 1
	pageSize = pageSize * 1
	const total = arr.length
	const pages = Math.floor((total + pageSize - 1) / pageSize)
	const start = pageSize * (pageNum - 1)
	const end = start + pageSize <= total ? start + pageSize : total
	const list = []
	for (var i = start; i < end; i++) {
		list.push(arr[i])
	}

	return {
		pageNum,
		total,
		pages,
		pageSize,
		list
	}
}

/**
 * 根据id获取时间戳
 *
 * @param {*} id
 * @returns
 */
function getTimeWithId(id) {
	// 这里为什么要乘以 1000 ？乘以1000之后表示“毫秒”。
	const time = parseInt(id.toString().substring(0, 8), 16) * 1000;
	// 这个是“秒”
	// const time = parseInt(id.toString().substring(0, 8), 16);

	return time;
}

/**
 * 走进永昌 数据的过滤器
 *
 * @param {*} result
 */
function goDataFilter(result) {
	// 这是“走进永昌/轮播图”，这个二级分类的id
	const categoryId1 = "5de328e2e887230e08f4fdf8";
	const swiper_imgs = result
		.filter(item => item.categoryId === categoryId1)
		.map(item => item.imgs)[0]

	// 这是“走进永昌/永昌服务”，这个二级分类的id
	const categoryId2 = "5de32f766896be05f40883b3";
	const listServe = result
		.filter(item => item.categoryId === categoryId2)
		.map(item => {
			const { _id, imgs, title, article } = item;
			const time = getTimeWithId(_id);
			return { img_list: imgs, text: { title, article }, time }
		})

	// 这是“走进永昌/案例展示”，这个二级分类的id
	const categoryId3 = "5de32f806896be05f40883b4";
	const listShow = result
		.filter(item => item.categoryId === categoryId3)
		.map(item => {
			const { _id, imgs, title, article } = item;
			const time = getTimeWithId(_id);
			return { img_list: imgs, text: { title, article }, time }
		})

	// 这是“走进永昌/咨询中心”，这个二级分类的id
	const categoryId5 = "5de32f956896be05f40883b6";
	const listAsk = result
		.filter(item => item.categoryId === categoryId5)
		.map(item => {
			const { _id, imgs, title, article, articleText } = item;
			const time = getTimeWithId(_id);
			return { img_list: imgs, text: { title, article, articleText }, time }
		})

	// 这是“走进永昌/关于永昌”，这个二级分类的id
	const categoryId4 = "5de32f8e6896be05f40883b5";
	const listAbout = result
		.filter(item => item.categoryId === categoryId4)
		.map(item => {
			const { _id, imgs, title, article, articleText } = item;
			const time = getTimeWithId(_id);
			return { img_list: imgs, text: { title, article, articleText }, time }
		})

	return { swiper_imgs, listServe, listShow, listAbout, listAsk }
}

/**
 * 检测数据库中是否有集合
 */
const testCreateModel = async testModel => {
	try {
		const count = await testModel.find().countDocuments();
		if (count > 0) return null;
		await testModel.createCollection();
	} catch (error) {
		console.log(error)
	}
}

module.exports = {
	pageFilter,
	getTimeWithId,
	goDataFilter,
	testCreateModel
}